package service

import (
	"beergo/app/admin/models"
	"beergo/lib/tool"
	"github.com/beego/beego/v2/client/orm/hints"
)

func GetUserMenu (user *models.AdminUser)([]*models.AdminMenu,[]int){
	isSAdmin := false
	if user.Id == 1 {
		isSAdmin = true
	}
	accessIdMap := make(map[int]bool)
	ids := make([]int,0)
	user.Load("Groups")
	for _, group := range user.Groups {
		println("group",group.Id)
		group.Load("Menus")
		for _, menu := range group.Menus {
			println("Menus",menu.Id)
			accessIdMap[menu.Id] = true
			ids = append(ids, menu.Id)
		}
	}
	menuRep := models.AdminMenuRepository{}
	roots,_ := menuRep.FindBy(tool.StringKeyMap{"parent__isnull": true},[]string{"sort"},0,0)
	userMenus := make([]*models.AdminMenu,0)
	for index, rootMenu := range roots {
		if isSAdmin {
			accessIdMap[rootMenu.Id] = true
		}
		find,ok:=accessIdMap[rootMenu.Id]
		if ok && find {
			userMenus = append(userMenus,scanTree(&roots[index],accessIdMap,isSAdmin))
		}
	}
	return userMenus,ids
}

func scanTree(menu *models.AdminMenu,mapper map[int]bool,isSAdmin bool) *models.AdminMenu{
	fitedMenu := make([]*models.AdminMenu,0)
	menu.GetOrm().LoadRelated(menu,"Children",hints.OrderBy("sort"))
	//menu.Load("Children")
	for _, sonMenu := range menu.Children {
		find,ok:=mapper[sonMenu.Id]
		if (ok && find) || isSAdmin {
			fitedMenu = append(fitedMenu,scanTree(sonMenu,mapper,isSAdmin))
		}
	}
	menu.Children = fitedMenu
	return menu
}


func GetUserPermission (user *models.AdminUser)string{
	return ""

}